package com.wilmer.TecherLessonPlan.preHandle;

import com.wilmer.common.constant.Constants;
import com.wilmer.common.core.domain.model.LoginUser;
import com.wilmer.common.core.redis.RedisCache;
import com.wilmer.common.enums.HttpMethod;
import com.wilmer.common.utils.StringUtils;
import com.wilmer.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Stephen
 */
@Component
@Slf4j
public class LessonPlanInterceptor implements HandlerInterceptor {

    @Value("${token.secret}")
    private String secret;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            log.info("这是OPTIONS请求,放行!");
            return true;
        }

        try {
            this.getLoginUser(request);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public LoginUser getLoginUser(HttpServletRequest request) {

        String token = request.getHeader("Authorization");

        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = tokenService.getTokenKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;
            }
            catch (Exception e)
            {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

}